package test.study.concurrent.thread._3_future.future;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import com.google.common.base.Stopwatch;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Slf4j
public class _2_Future_Main {

    private static ExecutorService POOL = Executors.newFixedThreadPool(100);

    @SneakyThrows
    public static void main(String[] args) {
        Stopwatch stopwatch = Stopwatch.createStarted();

        //step-1: init future list
        List<Future<String>> futureLt = ListUtil.toList();
        //step-2: execute _9_and save future
        for (int i = 1; i <= 4; i++) {
            final int taskId = i;
            futureLt.add(POOL.submit(() -> {
                int sec = RandomUtil.randomInt(1, 10);
                log.info("task[{}] sleep [{}] sec", taskId, sec);
                ThreadUtil.sleep(sec, TimeUnit.SECONDS);
                return String.format("task[%s] finish");
            }));
        }
        //step-3: get result
        futureLt.stream().forEach(f -> {
            try {
                log.info("{}", f.get());
            } catch (Exception ex) {
            }
        });

        log.info("耗时 {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
        POOL.shutdown();
    }
}
